import React, { Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Card,
  Col,
  Divider,
  Form,
  message,
  Row,
  Button,
  DatePicker,
  Radio,
  Select,
  Input,
  InputNumber,
  Modal,
  Switch,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from '../../styles/Manage.less';
import ImportModal from './component/ImportModal';
import DataModal from './component/DataModal';
import {
  ForecastTypeList,
  Lv1ClassifyTypeList,
  ActTypeList,
  NewGoodsTypeList,
} from '@/pages/Forecast/constants';
import ArrayUtils from '../../../utils/ArrayUtils';

const FormItem = Form.Item;

const FORECAST_TYPE_OBJ = ArrayUtils.toObject(
  ForecastTypeList,
  item => item.code,
  item => item.name
);

@Form.create()
@connect(({ forecastDimension: { cityList, warehouseList }, loading }) => ({
  dimCityList: cityList,
  dimWarehouseList: warehouseList,
  loading: loading.models.forecastScheduler,
}))
class OperationSchedulerList extends React.Component {
  state = {
    importModalVisible: false,
    dataModalVisible: false,
    item: {},
    queryParams: {
      forecastDate: moment()
        .add(1, 'days')
        .format('YYYY-MM-DD'),
      lv1ClassifyType: 0,
      forecastType: 0,
    },
  };

  // 表格字段
  columns = [
    {
      title: '日期',
      width: 160,
      fixed: 'left',
      align: 'center',
      render: (text, record) => <span>{record.forecastDate}</span>,
    },
    {
      title: '预测类型',
      width: 90,
      dataIndex: 'forecastType',
      render: text => FORECAST_TYPE_OBJ[text],
    },
    { title: '城市', width: 90, dataIndex: 'cityName' },
    { title: '仓库', width: 120, dataIndex: 'warehouseName' },
    { title: '1级分类', width: 120, dataIndex: 'lv1ClassifyName' },
    { title: 'SKU', width: 120, dataIndex: 'sku' },
    { title: 'SKU名称', width: 120, dataIndex: 'skuName' },
    { title: '活动类型', width: 120, dataIndex: 'actType' },
    {
      title: '是否新品',
      width: 120,
      dataIndex: 'newGoods',
    },
    { title: '建议销量', width: 120, dataIndex: 'adviseNum' },
    { title: '售价单价/斤(个)', width: 120, dataIndex: 'singlePrice' },
    { title: '成本价单价/斤(个)', width: 160, dataIndex: 'purchasePrice' },
    { title: '计价方式', width: 160, dataIndex: 'priceMode' },
    { title: '定价/份', width: 160, dataIndex: 'settlePrice' },
    { title: '最后操作人', width: 120, dataIndex: 'modifier' },
    {
      title: '最后修改时间',
      width: 120,
      dataIndex: 'modified',
      render: text => moment.unix(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      width: 160,
      align: 'center',
      fixed: 'right',
      dataIndex: 'option',
      render: (text, record) => (
        <Fragment>
          <Button
            type="primary"
            onClick={() => this.setState({ dataModalVisible: true, item: record })}
          >
            编辑
          </Button>
          <Button type="danger" onClick={() => this.handleDeleteById(record)}>
            删除
          </Button>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.listCity();
    this.listWarehouse();
    this.handleSearch();
  }

  listCity = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'forecastDimension/listCity',
    });
  };

  listWarehouse = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'forecastDimension/listWarehouse',
    });
  };

  onQueryParamsChange = (field, mapper = e => e) => val => {
    const { queryParams = {} } = this.state;
    this.setState(
      {
        queryParams: {
          ...queryParams,
          [field]: mapper(val),
        },
      },
      () => this.handleSearch()
    );
  };

  getQueryParams = () => {
    const { queryParams } = this.state;
    const params = { ...queryParams };
    if (queryParams.lv1ClassifyType !== 0) {
      params.lv1ClassifyType = queryParams.lv1ClassifyType;
    }

    return params;
  };

  // 查询操作
  handleSearch = (pagination = {}) => {
    const { dispatch } = this.props;
    const params = this.getQueryParams();
    dispatch({
      type: 'forecastScheduler/fetch',
      payload: {
        params,
        ...pagination,
      },
      callback: data => {
        this.setState({
          data,
        });
      },
    });
  };

  // 分页、过滤、排序处理
  handleStandardTableChange = pagination => {
    this.handleSearch({
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    });
  };

  handleDeleteById = ({ id }) => {
    const { dispatch } = this.props;
    Modal.confirm({
      title: '是否确认删除当前记录?',
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk: () => {
        dispatch({
          type: 'forecastScheduler/deleteById',
          payload: id,
          callback: data => {
            message.success(data);
            this.handleSearch();
          },
        });
      },
    });
  };

  renderOperation = () => {
    return (
      <Row gutter={{ md: 8, lg: 24, xl: 48 }} size="small">
        <Col>
          <div style={{ float: 'right' }}>
            <Button
              type="primary"
              onClick={() => this.setState({ dataModalVisible: true, item: {} })}
              style={{ marginRight: '10px' }}
            >
              新增
            </Button>

            <Button type="primary" onClick={() => this.setState({ importModalVisible: true })}>
              导入
            </Button>
          </div>
        </Col>
      </Row>
    );
  };

  renderCondition = () => {
    const {
      forecastDate,
      lv1ClassifyType,
      cityIdList,
      warehouseIdList,
      forecastType,
    } = this.getQueryParams();
    const { dimCityList, dimWarehouseList } = this.props;
    return (
      <Form layout="horizontal">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }} size="small">
          <Col md={8} sm={24}>
            <FormItem key="forecastType" label="预测类型">
              <Radio.Group
                value={forecastType}
                onChange={this.onQueryParamsChange('forecastType', e => e.target.value)}
              >
                {ForecastTypeList.map(item => (
                  <Radio.Button value={item.code} key={item.code}>
                    {item.name}
                  </Radio.Button>
                ))}
              </Radio.Group>
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem key="forecastDate" label="预测日期">
              <DatePicker
                value={forecastDate ? moment(forecastDate) : undefined}
                onChange={(date, dateStr) => this.onQueryParamsChange('forecastDate')(dateStr)}
                placeholder="选择日期"
              />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem key="lv1ClassifyType" label="一级类目">
              <Radio.Group
                value={lv1ClassifyType}
                onChange={this.onQueryParamsChange('lv1ClassifyType', e => e.target.value)}
              >
                {Lv1ClassifyTypeList.map(item => (
                  <Radio.Button value={item.code} key={item.code}>
                    {item.name}
                  </Radio.Button>
                ))}
              </Radio.Group>
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem key="cityList" label="城市">
              <Select
                value={cityIdList}
                placeholder="选择城市(支持多选)"
                allowClear
                mode="multiple"
                onChange={this.onQueryParamsChange('cityIdList')}
              >
                {dimCityList.map(item => (
                  <Select.Option value={item.code} key={item.id}>
                    {item.name}
                  </Select.Option>
                ))}
              </Select>
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem key="warehouseList" label="仓库">
              <Select
                value={warehouseIdList}
                placeholder="选择仓库(支持多选)"
                allowClear
                mode="multiple"
                onChange={this.onQueryParamsChange('warehouseIdList')}
              >
                {dimWarehouseList.map(item => (
                  <Select.Option value={item.code} key={item.id}>
                    {item.name}
                  </Select.Option>
                ))}
              </Select>
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem key="skuName" label="SKU名称">
              <Input
                onChange={this.onQueryParamsChange('skuName', e => e.target.value)}
                placeholder="请输入SKU名称"
              />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem key="sku" label="SKU">
              <InputNumber
                onChange={this.onQueryParamsChange('sku')}
                placeholder="请输入SKU"
                precision={0}
                style={{ width: '100%' }}
              />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem key="actType" label="活动类型">
              <Select
                placeholder="选择活动类型"
                allowClear
                onChange={this.onQueryParamsChange('actType')}
              >
                {ActTypeList.map(item => (
                  <Select.Option value={item.code} key={item.code}>
                    {`${item.name}(${item.code})`}
                  </Select.Option>
                ))}
              </Select>
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem key="newGoods" label="是否新品">
              <Select
                placeholder="选择是否新品"
                allowClear
                onChange={this.onQueryParamsChange('newGoods')}
              >
                {NewGoodsTypeList.map(item => (
                  <Select.Option value={item.code} key={item.code}>
                    {`${item.name}(${item.code})`}
                  </Select.Option>
                ))}
              </Select>
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem key="onlyModified" label="只看已修改">
              <Switch
                checkedChildren="是"
                unCheckedChildren="否"
                onChange={this.onQueryParamsChange('onlyModified')}
              />
            </FormItem>
          </Col>
        </Row>
      </Form>
    );
  };

  renderImportModal = () => {
    const { importModalVisible } = this.state;
    if (!importModalVisible) {
      return null;
    }
    return <ImportModal handleModalVisible={this.hideModalVisible('importModalVisible')} />;
  };

  hideModalVisible = field => (reload = false) => {
    this.setState({ [field]: false }, () => reload && this.handleSearch());
  };

  renderDataModal = () => {
    const { dataModalVisible, item } = this.state;
    if (!dataModalVisible) {
      return null;
    }
    return <DataModal handleModalVisible={this.hideModalVisible('dataModalVisible')} item={item} />;
  };

  render() {
    const { loading } = this.props;
    const { data } = this.state;
    let totalWidth = 0;
    this.columns.forEach(col => {
      const { width } = col;
      if (width) {
        totalWidth += width;
      }
    });

    // const rowSelection = {
    //   selectedRowKeys,
    //   onChange: this.onSelectChange,
    // };

    return (
      <PageHeaderWrapper title="运营计划表">
        <Card bordered={false}>
          <div className={styles.Manage}>
            <div className={styles.ManageForm}>
              {this.renderCondition()}
              <Divider type="horizontal" />
              {this.renderOperation()}
            </div>
            <StandardTable
              loading={loading}
              data={data}
              // rowSelection={rowSelection}
              scroll={{ x: totalWidth }}
              columns={this.columns}
              rowKey={record => record.id}
              onChange={this.handleStandardTableChange}
            />
          </div>
          {this.renderDataModal()}
          {this.renderImportModal()}
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default OperationSchedulerList;
